﻿using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Test
{





    public partial class LoginForm : UserControl
    {
        //MD5加密算法
        public static string GenerateMD5(string txt)
        {
            using (MD5 mi = MD5.Create())
            {
                byte[] buffer = Encoding.Default.GetBytes(txt);
                //开始加密
                byte[] newBuffer = mi.ComputeHash(buffer);
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < newBuffer.Length; i++)
                {
                    sb.Append(newBuffer[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }

        //验证码函数
        public static string GetCode(string username, string userwlanip, string wlanacip, string mac)
        {
            var time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            var secret = "Eshore!@#";
            var version = "214";
            var authenticatorToMd5 = version + userwlanip + wlanacip + mac + time + secret;
            var authenticator = (GenerateMD5(authenticatorToMd5)).ToUpper();
            var body = @"{""version"":""214"",""username"": """ + username + @""",""clientip"":""" + userwlanip + @""",""nasip"":""" + wlanacip + @""",""mac"":""" + mac + @""",""timestamp"":" + time + @",""authenticator"":""" + authenticator + @""",""iswifi"":""4060""}";
            var client = new RestClient("http://enet.10000.gd.cn:10001/client/vchallenge");
            client.Timeout = -1;
            client.FollowRedirects = false;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            // var body = @"{""version"":""214"",""username"":""1111"",""clientip"":""10.170.48.215"",""nasip"":""61.146.140.73"",""mac"":""84-A9-38-30-DB-B4"",""timestamp"":1646574938,""authenticator"":""CC1B0FD55B8C896D3D9B190DCEF229A7"",""iswifi"":""4060""}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            string resString = (response.Content).ToString();
            string[] codeOne = resString.Split('"');
            //Console.WriteLine(body);
            var code = codeOne[3];
            return ">" + code+">"+ body;
        }


        //登录函数
        public static string Login(string username, string userwlanip, string wlanacip, string mac, string code, string password)
        {
            var time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            var secret = "Eshore!@#";
            var authenticatorToMd5 = userwlanip + wlanacip + mac + time + code + secret;
            var authenticator = (GenerateMD5(authenticatorToMd5)).ToUpper();
            var client = new RestClient("http://61.140.12.23:10001/client/login");
            client.Timeout = -1;
            client.FollowRedirects = false;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            var body = @"{""username"":""" + username + @""",""password"":""" + password + @""",""clientip"":""" + userwlanip + @""",""nasip"":""" + wlanacip + @""",""mac"":""" + mac + @""",""timestamp"":" + time + @",""authenticator"":""" + authenticator + @""",""iswifi"":""1050"",""verificationcode"":""" + code + @"""}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            string resString = (response.Content).ToString();
            //string[] codeOne = resString.Split('"');
            //var loginRes = codeOne[3];
            //Console.WriteLine(resString);
            return resString;
        }


        //注销登录函数
        public static string Logout(string username, string userwlanip, string wlanacip, string mac)
        {
            var time = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000;
            var secret = "Eshore!@#";
            var authenticatorToMd5 = userwlanip + wlanacip + mac + time + secret;
            var authenticator = (GenerateMD5(authenticatorToMd5)).ToUpper();
            var client = new RestClient("http://61.140.12.23:10001/client/logout");
            client.Timeout = -1;
            client.FollowRedirects = false;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/json");
            var body = @"{""username"":""" + username + @""",""clientip"":""" + userwlanip + @""",""nasip"":""" + wlanacip + @""",""mac"":""" + mac + @""",""timestamp"":" + time + @",""authenticator"":""" + authenticator + @"""}";
            request.AddParameter("application/json", body, ParameterType.RequestBody);
            IRestResponse response = client.Execute(request);
            string resString = (response.Content).ToString();
            string[] codeOne = resString.Split('"');
            var loginRes = codeOne[7];
            return resString;
        }
        //

        public LoginForm()
        {
            InitializeComponent();

        }


        //初始化
        private void LoginForm_Load(object sender, EventArgs e)
        {
            string server = Dns.GetHostName();
            IPHostEntry heserver = Dns.GetHostEntry(server);
            string ip = (heserver.AddressList[1]).ToString();
            TxBUserip.Text = ip;
            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            TxBMac.Text = nics[0].GetPhysicalAddress().ToString();
            string pas = nics[0].GetPhysicalAddress().ToString();
            showForm1.TxBshowUsername.Text = "WLCB" + (pas.IndexOf("0") + 520 + 1314).ToString();

            FileInfo keyfile = new FileInfo("key.txt");
            if (keyfile.Exists == true)
            {
                StreamReader keyfileReader = new StreamReader("key.txt");
                string keyll = keyfileReader.ReadToEnd();
                keyfileReader.Close();
                showForm1.showTxBPassword.Text = keyll.Split(new char[] { '>' })[3];
            }

                FileInfo file = new FileInfo("配置.txt");
            if (file.Exists == true)
            {
                StreamReader parameter = new StreamReader("配置.txt");
                string pa = parameter.ReadToEnd();
                parameter.Close();
                string[] strarr = pa.Split(new char[] { '>' });
                txBUsername.Text = strarr[1];
                TxBPassword.Text = strarr[3];
                TxBUserip.Text = strarr[5];
                TxBSchool.Text = strarr[7];
                TxBMac.Text = strarr[9];
            }


        }


        //登录按钮
        private void button1_Click(object sender, EventArgs e)
        {
            if (showForm1.showTxBPassword.Text == GenerateMD5(showForm1.TxBshowUsername.Text) || showForm1.showTxBPassword.Text == "超级密码")
            {
                //读取配置文件
                FileInfo file = new FileInfo("配置.txt");
                if (file.Exists != true)
                {
                    //写入配置文件
                    StreamWriter paramWriter = new StreamWriter("配置.txt");
                    paramWriter.WriteLine(">" + showForm1.TxBshowUsername.Text + ">");
                    paramWriter.WriteLine(">" + showForm1.showTxBPassword.Text + ">");
                    paramWriter.WriteLine(">" + showForm1.showTxBUserip.Text + ">");
                    paramWriter.WriteLine(">" + showForm1.showTxBSchoolip.Text + ">");
                    paramWriter.WriteLine(">" + showForm1.showTxBMac.Text + ">");
                    paramWriter.WriteLine(">end\n账号\n密码\n设备IP\n学校IP\nMAc");
                    paramWriter.Flush();
                    paramWriter.Close();
                }
                else
                {
                    StreamReader parameter = new StreamReader("配置.txt");
                    string pa = parameter.ReadToEnd();
                    parameter.Close();
                    string[] strarr = pa.Split(new char[] { '>' });
                    string username = txBUsername.Text;
                    string password = TxBPassword.Text;
                    string userwlanip = TxBUserip.Text;
                    string wlanacip = TxBSchool.Text;
                    string mac = TxBMac.Text;
                    //
                    string rescode = GetCode(username, userwlanip, wlanacip, mac);
                    string[] codelog = rescode.Split(new char[] { '>' });
                    string code = codelog[1];
                    lalLoginTist.Text = "获取验证码中......";
                    Console.WriteLine(codelog[2]);
                    //

                    //
                    string Loginres = Login(username, userwlanip, wlanacip, mac, code, password);
                    string[] codeOne = Loginres.Split('"');
                    var loginRes = codeOne[3];
                    lalLoginTist.Text = loginRes;
                    Console.WriteLine(loginRes);
                    if (loginRes == "login success")
                    {
                        lalLoginTist.Text = "登录成功！";
                    }
                    else
                    {
                        StreamWriter loginlog = new StreamWriter("log.txt");
                        loginlog.WriteLine("Body:" + rescode + "\n" + "Login" + Loginres);
                        loginlog.Close();
                        lalLoginTist.Text = "登录失败！";
                    }
                }
            }
            else
            {
                var frm = new ShowWindowForm();
                frm.TxBtise.Text = "请先程序验证";
                frm.ShowDialog();
            }  
        }










        private void txBUsername_TextChanged(object sender, EventArgs e)
        {
            showForm1.TxBshowUsername.Text = txBUsername.Text;
        }
        private void TxBPassword_TextChanged(object sender, EventArgs e)
        {
            showForm1.showTxBPassword.Text = TxBPassword.Text;
        }
        private void TxBUserip_TextChanged(object sender, EventArgs e)
        {
            showForm1.showTxBUserip.Text = TxBUserip.Text;
        }
        private void TxBSchool_TextChanged(object sender, EventArgs e)
        {
            showForm1.showTxBSchoolip.Text = TxBSchool.Text;
        }
        private void TxBMac_TextChanged(object sender, EventArgs e)
        {
            showForm1.showTxBMac.Text = TxBMac.Text;
        }
        private void ckBoxPassword_CheckedChanged(object sender, EventArgs e)
        {
            if (ckBoxPassword.Checked)
            {
                TxBPassword.PasswordChar = '\0';
                showForm1.showTxBPassword.PasswordChar = '\0'; //显示输入
            }
            else
            {
                TxBPassword.PasswordChar = '*';
                showForm1.showTxBPassword.PasswordChar = '*';   //显示*
            }
        }

        private void BtLogout_Click(object sender, EventArgs e)
        {
            StreamReader parameter = new StreamReader("配置.txt");
            string pa = parameter.ReadToEnd();
            parameter.Close();
            string[] strarr = pa.Split(new char[] { '>' });
            string username = txBUsername.Text;
            string password = TxBPassword.Text;
            string userwlanip = TxBUserip.Text;
            string wlanacip = TxBSchool.Text;
            string mac = TxBMac.Text;
            string resLogout = Logout(username, userwlanip, wlanacip, mac);
            Console.WriteLine(resLogout);
            if (resLogout == "logout success")
            {
                lalLoginTist.Text = "logout success";
            }
            else
            {
                lalLoginTist.Text = "logout false";
            }
        }

        private void showForm1_Load(object sender, EventArgs e)
        {

        }
    }
}
